<?php

/** 
 * @author sifat
 * 
 * @doc https://dev.twitter.com/docs/api/1/get/search
 */

class twitter extends BaseClass{
        
        public $url='http://search.twitter.com/search.json';
        
        function __construct($data, $EE) {
            parent::__construct($data, $EE);
            $this->options=$this->apiOptions('twitter');
        }
        
        /*
         * generate url for twitter get search
         */
        function generateUrl(){
            $this->url .= '?q='.urlencode(implode("&", $this->keyword));
            if($this->options['geocode']==1){
                $this->url.='?geocode='.$this->options['latituted'].','.$this->options['logituted'].','.$this->options['radius'].$this->options['unit'];
            }
            $this->url.='&lang='.$this->options['lang'];
            
        }

        function getData(){
            if(!$this->options){
                return array();
            }
            $this->formateData();
            
            if(empty ($this->insertData)){
                return array();
            }
            
            return $this->insertData;
        }
        
        /*
         * get results from twitter
         */
        function searchReasults(){
            $this->generateUrl();
            return json_decode(file_get_contents($this->url));
        }
        
        /*
         * creating array for enrty
         */
        function formateData(){
            $searchReasults=$this->searchReasults();
            
            if(!$searchReasults){
                return false;
            }
                
            
            $fields=$this->getFields('twitter');
            if($fields){
                //$fields=unserialize($fields['fields']);
            
                $i=0;
                if(!empty ($searchReasults)){
                    foreach ($searchReasults->results as $result){
                        //pr($result);

                            foreach($fields as $key=>$value){
                                if (substr($key, 0, strpos($key, '_'))!='fmt'){
                                    $this->insertData[$i]['field_id_'.$value]=$result->$key;
                                    $this->insertData[$i]['field_ft_'.$value]=$fields['fmt_'.$key];
                                    $this->insertData[$i]['title']='twitter-'.implode("&", $this->keyword) . '-at-' . date('Y-m-d', time()) .'-'. rand(0, 9999);
                                    $this->insertData[$i]['entry_date']=time();

                                }
                            }
                            $i++;
                        }
                }
            }
           
        }
}